﻿#include "JgaiBar004.h"

#include <QDateTime>
#include <map>

class _helperData {
    // infosize:正文大小, tsize:时间字大小，infoco:正文颜色，bgco:背景颜色
    int infosize;
    int tsize;
    QString infoco;
    QString bgc;

   public:
    _helperData();
    int nMsg;  //消息条数
    QString _htmlBeginString, _htmlEndString, _htmlMsgString;
    QString _genMsg(QString tx, QString color = "green");
    void setFormat(int infosize, int bsize, QString infoco, QString bgc);
};

_helperData::_helperData() {
    nMsg = 0;
    setFormat(19, 6, "#888", "#f0f0f0");
}

QString _helperData::_genMsg(QString tx, QString color) {
    QDateTime dt = QDateTime::currentDateTime();
    QTime tt = dt.time();

    QString fmat;
    if (tt.hour() == 0)
        fmat = "yy-MM-dd hh:mm:ss";
    else
        fmat = "hh:mm:ss";

    QString a = "<div><a class='cc'>" + dt.toString(fmat) + "</a>";

    a += "<a style='color:" + color + "'> " + tx + "</a></div>";
    return a;
}
void _helperData::setFormat(int infosize0,
                            int tsize0,
                            QString infoco0,
                            QString bgc0) {
    infosize = infosize0;
    tsize = tsize0;
    infoco = infoco0;
    bgc = bgc0;
    _htmlBeginString =
        QString(
            "<!DOCTYPE html>"
            " <html lang='zh-CN'>"
            " <head>"
            "  <meta charset='UTF-8'>"
            "  <title>{title}</title>"
            " <style>"
            "     .cc{font-size:") +
        QString::number(tsize) + ("px;color:") + infoco +
        ("}"
         "    #info{font-size:") +
        QString::number(infosize) +
        ("px;width: 100%;word-wrap:break-word;word-break:break-all;}"
         " </style>"
         "</head>"
         "<body style='background-color:") +
        bgc +
        (";'>"
         " <div id='info'>");

    _htmlEndString = "</div> </body> </html>";
}

int _tik = 0;
std::map<int, _helperData*> _dat;
#define D _dat[_id]

JgaiBar004::JgaiBar004(QWidget* parent)
    : QTextEdit(parent)

{
    _id = _tik++;
    D = new _helperData();
    setReadOnly(true);
}

JgaiBar004::~JgaiBar004() {
    delete _dat[_id];
    _dat.erase(_id);
}
int JgaiBar004::addInfo(QString tx, QString color) {
    D->_htmlMsgString += D->_genMsg(tx, color);
    setHtml(D->_htmlBeginString + D->_htmlMsgString + D->_htmlEndString);
    moveCursor(QTextCursor::End);
    return ++(D->nMsg);
}

void JgaiBar004::clear() {
    D->_htmlMsgString = "";
    setHtml(D->_htmlBeginString + D->_htmlMsgString + D->_htmlEndString);
    D->nMsg = 0;
}

void JgaiBar004::setFormat(int infosize,
                           int tsize,
                           QString infoco,
                           QString bgc) {
    D->setFormat(infosize, tsize, infoco, bgc);
    setHtml(D->_htmlBeginString + D->_htmlMsgString + D->_htmlEndString);
}
